using System.Collections.Generic;
using System.Windows.Forms;
using Mbs.Elements;
using Mbs.Globalization;
using Mbs.Modularity.AddIns;
using Mbs.ComponentModel.Container;

namespace Mbs.Windows.Elements.Builders
{
    static class AddInItemExtension
    {
        public static bool IsSite(this IAddInItem element)
        {
            //return !element.Properties.Get<bool>("IsLeaf", true);
            return element.Items == null || element.Items.Count == 0;
        }
    }

    [Component(Id = "ToolStrip.DropDown.Button", Service = typeof(IElementBuilder))]
    public class ToolStripDropDownButtonBuilder : ToolStripItemBuilder<ToolStripDropDownButton>
    {
        protected override ToolStripDropDownButton CreateItem(IAddInItem addInItem)
        {
            return new MbsToolStripDropDownButton(addInItem);
        }

        private class MbsToolStripDropDownButton : ToolStripDropDownButton, Mbs.Globalization.ISupportGlobalization, IAddInItemHost
        {
            public IAddInItem AddInItem { get; private set; }
            public MbsToolStripDropDownButton(IAddInItem addInItem)
            {
                AddInItem = addInItem;
                IsSupportGlobalization = true;

                this.Initialize(addInItem);
                InitializeResource();
            }


            public bool IsSupportGlobalization { get; set; }

            public void InitializeResource()
            {
                Text = StringParser.Parse(AddInItem.Label);
                Image = AddInItem.Properties.Contains("Icon") ? ResourceRepository.Images.Get(AddInItem.Properties.Get<string>("Icon")) : null;
                if (AddInItem.Properties.Contains("ToolTip"))
                    ToolTipText = StringParser.Parse(AddInItem.Properties.Get<string>("ToolTip"));
            }

            public void RefreshResource()
            {
                InitializeResource();
            }
        }

        protected override void OnInitInstance(object caller, IAddInItem element, List<object> subItems, ToolStripItem instance)
        {
            var dropDownItem = instance as ToolStripDropDownItem;
            if (dropDownItem != null)
            {
                //if (element.IsSite())
                    ElementService.Sites.RegisterSite(element.Path, dropDownItem);

                foreach (var o in subItems)
                    if (o is ToolStripItem)
                        ElementService.Sites[element.Path].Add(o, null);

                //TODO:??
                BindCommand(element, dropDownItem, "Click");
            }
        }
    }
}
